import Vue from 'vue';
import VueRouter from 'vue-router';

//解决多次点击bug
const VueRouterPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(to) {
    return VueRouterPush.call(this, to).catch(err => err);
}

const VueRouterReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function push(to) {
    return VueRouterReplace.call(this, to).catch(err => err);
}

Vue.use(VueRouter);
//定义路由规则
const routes = [
    //重定向
    {
        path:"/",
        redirect:"/login"
    },
    {
        path:'/My.vue/:id/:name',
        name:'My',
        component:()=>import("@/views/My.vue"),
        props:true
    },
    {
        path:"/login",
        name:"login",
        component:()=>import("@/views/Login.vue"),
        meta:{
            title:"登录",
        },
    },
    {
        path:"/home",
        name:"home",
        component:()=>import("@/views/home/index.vue"),
        meta:{
            isAuth:true,
            title:"首页",
            roles:['admin','vip','svip'],
        },
        children:[
            {
                path:"a",
                name:"A",
                component:()=>import("@/views/home/A.vue"),
            },
            {
                path:"b/:id/:name",
                name:"B",
                component:()=>import("@/views/home/B.vue"),
            },
            {
                path:"c/:id/:name",
                name:"C",
                component:()=>import("@/views/home/C.vue"),
                // props传参
                // props:{id:'6',name:'小明'}
                //动态参数params
                // props:true,
                //第三种函数
                props($route){
                    return {
                        id:$route.params.id,
                        name:$route.params.name,
                        age:$route.query.age
                    }
                }


            },
        ]
    },
];
const router = new VueRouter({
    mode: 'history',
    routes,
})

//全局路由守卫
//to: 到那个组件 from: 启始组件  next: 放行
router.beforeEach((to,from,next)=>{
    //如果目标路径与当前路径相同，则直接放行
    console.log("to",to.path);
    const userRole = 'vip';
    //检查路由是否需要认证
    if (to.matched.some(record => record.meta.isAuth)) {
        // 检查用户角色是否满足路由要求
        if (to.meta.isAuth && !to.meta.roles.includes(userRole)) {
            // 如果用户角色不是管理员，则重定向到登录页面
            next({ name: 'login' });
        } else {
            // 用户角色匹配，允许访问
            // 设置页面标题
            document.title = to.meta.title || '默认标题';
            next();
        }
    } else {
        // 不需要认证的路由，直接允许访问
        document.title = to.meta.title || '默认标题';
        next();
    }

    
})

export default router;
